package com.zlzsy.app.base.ui

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.afollestad.materialdialogs.MaterialDialog
import com.zlzsy.app.base.R
import com.zlzsy.app.base.presenter.BasePresenter
import com.zlzsy.app.base.ui.interfaces.IActivity
import com.zlzsy.app.base.ui.interfaces.IFragment
import org.jetbrains.anko.support.v4.toast

/**
 * Created by niantuo on 2017/11/6.
 * 所有fragment 的基类
 */
open class BaseFragment<P : BasePresenter> : Fragment(), IFragment {

    protected var mPresenter: P? = null
    private var mView: View? = null

    override fun showLoadingDialog() {
        (context as? IActivity)?.showLoadingDialog()
    }

    override fun hideLoadingDialog() {
        (context as? IActivity)?.hideLoadingDialog()
    }

    override fun showAlert(msg: String) {
        toast(msg)
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mView = createView()
        return mView
    }

    open fun createView(): View? = null
    override fun getView(): View? = mView

    open protected fun createPresenter(): P? = null

    override fun showConfirm(msg: String, callback: (Boolean) -> Unit) {
        MaterialDialog.Builder(context)
                .content(msg)
                .positiveText(R.string.confirm)
                .negativeText(R.string.cancel)
                .onPositive { _, _ ->
                    callback.invoke(true)
                }
                .onNegative { _, _ ->
                    callback.invoke(false)
                }
                .show()
    }


    override fun onBackPressed(): Boolean = false

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            activity.finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }


    fun finish() {
        activity.finish()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPresenter = createPresenter()
        mPresenter?.onCreate()
    }

    override fun onResume() {
        super.onResume()
        mPresenter?.onResume()
    }

    override fun onPause() {
        super.onPause()
        mPresenter?.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter?.onDestroy()
    }

}